package conn

import (
	"##PROJECT##/config/vars"
	"##PROJECT##/core/cHelper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"time"
)

type BaseModel struct {
	Driver string
}

func (i *BaseModel) Db(driver string) *gorm.DB {
	i.Driver = driver
	return connectToDatabase(driver)
}

func (i *BaseModel) Model(value interface{}) *gorm.DB {
	c := connectToDatabase(i.Driver)

	return c.Model(value)
}

func (i *BaseModel) Table(name string, args ...interface{}) *gorm.DB {
	c := connectToDatabase(i.Driver)

	return c.Table(name, args...)
}

var dbs = make(map[string]*gorm.DB)

func connectToDatabase(driver string) *gorm.DB {
	if _, ok := dbs[driver]; ok && dbs[driver] != nil {
		return dbs[driver]
	}
	if driver == "" {
		driver = vars.Database.Driver
	}
	var err error
	dbconf := vars.Database
	//driver := dbconf.Driver
	channels := dbconf.Channels

	_, defualtOK := channels[driver]
	if channels == nil || !defualtOK {
		//panic("database config driver is not set")
		log.Panicf("database config driver[%s] is not set", driver)
	}

	driverConf := channels[driver]
	var dsn = driverConf.Dsn
	if dsn == "" {
		dsn = driverConf.Username + ":" +
			driverConf.Password + "@tcp(" +
			driverConf.Host + ":" +
			cHelper.ToString(driverConf.Port) + ")/" +
			driverConf.Database + "?charset=" +
			driverConf.Charset
	}
	conn := mysql.Open(dsn)
	dbs[driver], err = gorm.Open(conn, &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
	})
	if err != nil {
		panic("database connection err: " + err.Error())
	}
	sqlDB, err := dbs[driver].DB()
	if err != nil {
		panic("database connection pool err: " + err.Error())
	}
	sqlDB.SetMaxIdleConns(driverConf.MaxIgleConns)
	sqlDB.SetMaxOpenConns(driverConf.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Second * time.Duration(driverConf.ConnMaxLifetime))

	return dbs[driver]
}
